package _2022.hot100._146_LRU缓存;

import java.util.HashMap;
import java.util.Map;

/**
 * @author： YHSimon
 * @date： 2022-05-05 11:18
 */
public class LRUCache {
    class DLinkedNode{
        int key;
        int value;
        DLinkedNode pre;
        DLinkedNode next;
        public DLinkedNode(){}
        public DLinkedNode(int key,int value){
            this.key=key;
            this.value=value;
        }
    }


    private Map<Integer,DLinkedNode> cache=new HashMap<>();
    private int size;
    private int capacity;
    private DLinkedNode head,tail;

    public LRUCache(int capacity){
        this.size=0;
        this.capacity=capacity;
        this.head=new DLinkedNode();
        this.tail=new DLinkedNode();
        head.next=tail;
        tail.pre=head;
    }

    public void put(int key,int value){
        DLinkedNode node=cache.get(key);
        if(null==node){
            DLinkedNode newNode = new DLinkedNode(key, value);
            cache.put(key, newNode);
            addToHead(newNode);
            size++;
            if(size>capacity){
                DLinkedNode tail = removeTail();
                cache.remove(tail.key);
                size--;
            }
        }else{
            node.value=value;
            moveToHead(node);
        }
    }

    private DLinkedNode removeTail() {
        DLinkedNode res=tail.pre;
        removeNode(res);
        return res;
    }

    public int get(int key){
        DLinkedNode node = cache.get(key);
        if(null==node) return -1;
        moveToHead(node);
        return node.value;
    }

    private void moveToHead(DLinkedNode node) {
        removeNode(node);
        addToHead(node);
    }

    private void addToHead(DLinkedNode node) {
        node.pre = head;
        node.next = head.next;
        head.next.pre = node;
        head.next = node;
    }
    private void removeNode(DLinkedNode node) {
        node.pre.next=node.next;
        node.next.pre=node.pre;
    }
}
